package com.wangtao.firstapp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.wangtao.firstapp.R;
import com.wangtao.firstapp.adapters.CommentsListAdapter;
import com.wangtao.firstapp.modles.ArticleDetailsData;
import com.wangtao.firstapp.modles.CommentsListData;
import com.wangtao.firstapp.modles.PeopleAllSee;
import com.wangtao.firstapp.utils.HttpUtils;

import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 新鲜原创下的二级页面
 * 复用文章页面下RecyclerView的实体类和适配器
 * Created by lanouhn on 16/9/12.
 */
public class NewestSecondryActivity extends AppCompatActivity {
    private ImageView iv_bigpic, iv_header, iv_shop, iv_back_secondry_article_details_white;
    private TextView tv_title, tv_author, tv_views, tv_title1, item_name_sife_second_view_one, price_name_sife_second_view_one, likes_tv_sife_second_view;
    private ArticleDetailsData detailsdata;// 文章详情实体类
    private PeopleAllSee peopleAllSee;// 大家都在看实体类
    private CommentsListData commentsListData;// 评论实体类
    private LinearLayout linearLayout_act_main;// 用来动态加载控件的线性布局
    private CommentsListAdapter commentsListAdapter;// 用来加载文章下方评论的适配器
    private ScrollView scrollview_comments;// 包裹RecyclerView的ScrollView
    private LinearLayout comment_linearlayout;// 加载评论的LinearLayout
    private TextView tv_commenttitle_articledetails;
    private ImageButton shop_sife_second_view_one;
    private RelativeLayout relativeLayout;//

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_details);
        initView();
        initData();
        initEvent();
    }

    private void initView() {
        linearLayout_act_main = (LinearLayout) findViewById(R.id.linearLayout_act_main);
        iv_bigpic = (ImageView) findViewById(R.id.iv_bigpic);
        iv_header = (ImageView) findViewById(R.id.civ_header_article_details);
        tv_title = (TextView) findViewById(R.id.tv_title_article_details);
        tv_author = (TextView) findViewById(R.id.tv_author_article_details);
        tv_views = (TextView) findViewById(R.id.tv_views_article_details);
        iv_back_secondry_article_details_white = (ImageView) findViewById(R.id.iv_back_secondry_article_details_white);
        scrollview_comments = (ScrollView) findViewById(R.id.scrollview_comments);
        comment_linearlayout = (LinearLayout) findViewById(R.id.comment_linearlayout);
        tv_commenttitle_articledetails = (TextView) findViewById(R.id.tv_commenttitle_articledetails);
    }

    private void initData() {
        Intent intent = getIntent();
        // 图文详情
        String url = intent.getStringExtra("url");
        String param = intent.getStringExtra("param");
        try {
            HttpUtils.doPostAsyn(url, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    detailsdata = gson.fromJson(result, ArticleDetailsData.class);
                    if (detailsdata.getData().getContent_list().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 大家都在看
        String url1 = intent.getStringExtra("url1");
        String param1 = intent.getStringExtra("param1");
        try {
            HttpUtils.doPostAsyn(url1, param1, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson1 = new Gson();
                    peopleAllSee = gson1.fromJson(result, PeopleAllSee.class);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 评论
        String url2 = intent.getStringExtra("url2");
        String param2 = intent.getStringExtra("param2");
        try {
            HttpUtils.doPostAsyn(url2, param2, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson2 = new Gson();
                    commentsListData = gson2.fromJson(result, CommentsListData.class);
                    if (commentsListData.getData().size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initEvent() {
        // 页面左上角返回按钮
        iv_back_secondry_article_details_white.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 点击作者头像跳转到作者个人信息界面
        iv_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userid = detailsdata.getData().getUser().getUser_id();
                Intent intent = new Intent(NewestSecondryActivity.this, UserInfoActivity.class);
                intent.putExtra("userid", userid);
                startActivity(intent);
            }
        });
        // 点击作者昵称同样跳转到作者个人信息界面
        tv_author.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userid = detailsdata.getData().getUser().getUser_id();
                Intent intent = new Intent(NewestSecondryActivity.this, UserInfoActivity.class);
                intent.putExtra("userid", userid);
                startActivity(intent);
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    // Toast.makeText(ArticleDetails.this, "网络访问失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    // 加载图文详情
                    ArticleDetailsData.DataBean databean = detailsdata.getData();
                    ArticleDetailsData.DataBean.UserBean userbean = detailsdata.getData().getUser();
                    final List<ArticleDetailsData.DataBean.ContentListBean> contentlist = detailsdata.getData().getContent_list();
                    if (!"".equals(databean.getPic())) {
                        iv_bigpic.setVisibility(View.VISIBLE);
                        Picasso.with(NewestSecondryActivity.this).load(databean.getPic()).config(Bitmap.Config.RGB_565).into(iv_bigpic);
                    }
                    tv_title.setText(databean.getTitle());
                    Picasso.with(NewestSecondryActivity.this).load(userbean.getAvatar()).config(Bitmap.Config.RGB_565).into(iv_header);
                    tv_author.setText(userbean.getNickname());
                    tv_views.setText(databean.getViews());
                    for (int i = 0; i < contentlist.size(); i++) {
                        if (contentlist.get(i).getType() == 1) {
                            ImageView imageView = new ImageView(NewestSecondryActivity.this);
                            //imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                            Picasso.with(NewestSecondryActivity.this).load(contentlist.get(i).getImage_url()).config(Bitmap.Config.RGB_565).into(imageView);
                            linearLayout_act_main.addView(imageView);
                            TextView textView = new TextView(NewestSecondryActivity.this);
                            textView.setText(contentlist.get(i).getImage_desc());
                            linearLayout_act_main.addView(textView);
                        }
                        if (contentlist.get(i).getType() == 2) {
                            TextView textView = new TextView(NewestSecondryActivity.this);
                            textView.setText(contentlist.get(i).getText_content());
                            textView.setLineSpacing(1, 1.5f);
                            linearLayout_act_main.addView(textView);
                        }
                        if (contentlist.get(i).getType() == 5) {
                            View view = LayoutInflater.from(NewestSecondryActivity.this).inflate(R.layout.sife_second_view_one, null);
                            iv_shop = (ImageView) view.findViewById(R.id.iv_shop);
                            tv_title1 = (TextView) view.findViewById(R.id.tv_title1);
                            item_name_sife_second_view_one = (TextView) view.findViewById(R.id.item_name_sife_second_view_one);
                            price_name_sife_second_view_one = (TextView) view.findViewById(R.id.price_name_sife_second_view_one);
                            likes_tv_sife_second_view = (TextView) view.findViewById(R.id.likes_tv_sife_second_view);

                            // 点击跳转到单品详情
                            relativeLayout = (RelativeLayout) view.findViewById(R.id.re_sife_second_view_one);
                            final int finalI = i;
                            relativeLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(NewestSecondryActivity.this, ShopDetailsActivity.class);
                                    String shop_ID = contentlist.get(finalI).getProduct_id();
                                    intent.putExtra("shop_iD", shop_ID);
                                    startActivity(intent);
                                }
                            });

                            shop_sife_second_view_one = (ImageButton) view.findViewById(R.id.shop_sife_second_view_one);
                            final int finalI1 = i;
                            shop_sife_second_view_one.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    String url = contentlist.get(finalI1).getUrl() + ".html";
                                    Intent intent = new Intent(NewestSecondryActivity.this, ArticleGuidePicture.class);
                                    intent.putExtra("url", url);
                                    startActivity(intent);
                                }
                            });

                            Picasso.with(NewestSecondryActivity.this).load(contentlist.get(i).getPic()).config(Bitmap.Config.RGB_565).into(iv_shop);
                            tv_title1.setText(contentlist.get(i).getItem_subtitle());
                            item_name_sife_second_view_one.setText(contentlist.get(i).getItem_name());
                            price_name_sife_second_view_one.setText(contentlist.get(i).getPrice());
                            if (!"".equals(contentlist.get(i).getLikes())) {
                                likes_tv_sife_second_view.setText(contentlist.get(i).getLikes());
                            } else {
                                likes_tv_sife_second_view.setText("0");
                            }

                            linearLayout_act_main.addView(view);
                        }
                    }
                    TextView textView = new TextView(NewestSecondryActivity.this);
                    textView.setText("创建于 " + detailsdata.getData().getCreate_time_str() + "     " + "收藏 " + detailsdata.getData().getLikes());
                    linearLayout_act_main.addView(textView);

                    // 加载图文与大家都在看 中间的视图
                    View view = LayoutInflater.from(NewestSecondryActivity.this).inflate(R.layout.quick_follow_author, null);
                    CircleImageView civ_quick_follow_author = (CircleImageView) view.findViewById(R.id.civ_quick_follow_author);
                    TextView tv_authorname = (TextView) view.findViewById(R.id.tv_authorname);

                    Picasso.with(NewestSecondryActivity.this).load(detailsdata.getData().getUser().getAvatar()).config(Bitmap.Config.RGB_565).into(civ_quick_follow_author);
                    tv_authorname.setText(detailsdata.getData().getUser().getNickname());
                    linearLayout_act_main.addView(view);

                    // 加载大家都在看视图
                    if (peopleAllSee.getData() != null) {
                        for (int i = 0; i < peopleAllSee.getData().getTopic().size(); i++) {
                            View view1 = LayoutInflater.from(NewestSecondryActivity.this).inflate(R.layout.peopleallsee, null);
                            ImageView iv_peopleallsee = (ImageView) view1.findViewById(R.id.iv_peopleallsee);
                            TextView tv_peopleallsee = (TextView) view1.findViewById(R.id.tv_peopleallsee);
                            TextView tv_title_peopleallsee = (TextView) view1.findViewById(R.id.tv_title_peopleallsee);
                            if ("".equals(peopleAllSee.getData().getTopic().get(i).getPic())) {
                                Picasso.with(NewestSecondryActivity.this).load(peopleAllSee.getData().getTopic().get(i).getPics().get(0).getUrl()).config(Bitmap.Config.RGB_565).into(iv_peopleallsee);
                            } else if ("".equals(peopleAllSee.getData().getTopic().get(i).getPics())) {
                                Picasso.with(NewestSecondryActivity.this).load(peopleAllSee.getData().getTopic().get(i).getPic()).config(Bitmap.Config.RGB_565).into(iv_peopleallsee);
                            }
                            if (i > 0) {
                                tv_peopleallsee.setVisibility(View.GONE);
                            }
                            tv_title_peopleallsee.setText(peopleAllSee.getData().getTopic().get(i).getTitle());
                            iv_peopleallsee.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                            tv_title_peopleallsee.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                            linearLayout_act_main.addView(view1);
                        }
                    }
                    break;
                case 2:
                    // 加载评论
                    if ("".equals(commentsListData.getData())) {
                        tv_commenttitle_articledetails.setVisibility(View.GONE);
                    }

                    for (int i = 0; i < commentsListData.getData().size(); i++) {
                        View view_comment = LayoutInflater.from(NewestSecondryActivity.this).inflate(R.layout.item_comments_commentslist, null);
                        TextView tv_user_comments = (TextView) view_comment.findViewById(R.id.tv_user_comments);// 评论item中的评论
                        ImageView iv_header_commentslist = (ImageView) view_comment.findViewById(R.id.iv_header_commentslist);// 评论item中的头像
                        TextView tv_datestr = (TextView) view_comment.findViewById(R.id.tv_datestr);// 评论item中的时间
                        TextView tv_username_author = (TextView) view_comment.findViewById(R.id.tv_username_author);// 评论item中的用户名
                        TextView isauthor = (TextView) view_comment.findViewById(R.id.isauthor);// 评论item中是否为作者的标识

                        // 直接加载所有评论
//                         Picasso.with(ArticleDetails.this).load(commentsListData.getData().get(i).getUser().getAvatar()).into(iv_header_commentslist);
//                         tv_datestr.setText(commentsListData.getData().get(i).getDatestr());
//                         tv_username_author.setText(commentsListData.getData().get(i).getUser().getNickname());
//                        tv_user_comments.setText(commentsListData.getData().get(i).getConent());
//                        tv_username_author.setText(commentsListData.getData().get(i).getUser().getNickname());

                        // 加载回复评论
                        if (commentsListData.getData().get(i).getAt_user().getNickname() != null) {

                            String string = commentsListData.getData().get(i).getAt_user().getNickname();
                            String content = "回复 @" + commentsListData.getData().get(i).getAt_user().getNickname() + ":" + commentsListData.getData().get(i).getConent();
                            SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content);
                            spannableStringBuilder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.mycolor)), 2, string.length() + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            tv_user_comments.setText(spannableStringBuilder);
                            Picasso.with(NewestSecondryActivity.this).load(commentsListData.getData().get(i).getUser().getAvatar()).config(Bitmap.Config.RGB_565).into(iv_header_commentslist);
                            tv_username_author.setText(commentsListData.getData().get(i).getUser().getNickname());
                        } else {
                            Picasso.with(NewestSecondryActivity.this).load(commentsListData.getData().get(i).getUser().getAvatar()).config(Bitmap.Config.RGB_565).into(iv_header_commentslist);
                            tv_datestr.setText(commentsListData.getData().get(i).getDatestr());
                            tv_user_comments.setText(commentsListData.getData().get(i).getConent());
                            tv_username_author.setText(commentsListData.getData().get(i).getUser().getNickname());
                        }
                        comment_linearlayout.addView(view_comment);
                    }
                    break;
            }
            ;
        }
    };
}
